package com.study.myupdate.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import androidx.core.content.FileProvider;

import org.conscrypt.BuildConfig;

import java.io.File;

/**
 * 更新使用到的工具类
 */
public class UpdateUtil {
    /**
     * 获取当前App的版本号
     *
     * @param context
     * @return
     */
    public static long getAppVersion(Context context) {
        long version = 0;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
            PackageManager packageManager = context.getPackageManager();
            try {
                PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
                version = packageInfo.versionCode;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            PackageManager packageManager = context.getPackageManager();
            try {
                PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
                version = packageInfo.getLongVersionCode();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return version;
    }


    /**
     * 获取当前应用包名
     *
     * @param context
     * @return
     */
    public static String getPackageName(Context context) {
        return context.getPackageName();
    }

    /**
     * 获取app文件的包名
     *
     * @param context
     * @param apkPath
     * @return
     */
    public static String getApkPackageNameFroPath(Context context, String apkPath) {
        LogUtil.i("apkPath:" + apkPath);
        if (fileExists(apkPath)) {
            PackageManager pm = context.getPackageManager();
            PackageInfo info = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
            if (info != null) {
                ApplicationInfo appInfo = info.applicationInfo;
//                String packageName = appInfo.packageName;  //得到安装包名称
//                String version = info.versionName;//获取安装包的版本号
                try {
                    LogUtil.i(appInfo.packageName);
                    return appInfo.packageName;
                } catch (OutOfMemoryError e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
        LogUtil.i("appNameApk:" + null);
        return null;
    }

    /**
     * 获取app版本号
     *
     * @param context
     * @param apkPath
     * @return
     */
    public static Long getApkVersionCodeFroPath(Context context, String apkPath) {
        long version = 0;
        if (fileExists(apkPath)) {
            PackageManager pm = context.getPackageManager();
            PackageInfo info = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
            if (info != null) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
                    try {
                        version = info.versionCode;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        version = info.getLongVersionCode();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        }
        LogUtil.i("version:" + version);
        return version;
    }


    /**
     * 获取当前应用包名
     *
     * @param context
     * @return
     */
    public static String getApkName(Context context) {
        String appName = null;
        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            appName = packageInfo.packageName;
        } catch (Exception e) {
            e.printStackTrace();
        }

        LogUtil.i("appNameCurrent:" + appName);
        return appName;
    }


    /**
     * 文件是否存在
     *
     * @param filePath
     * @return
     */
    public static boolean fileExists(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            LogUtil.i("存在:" + filePath);
            return true;
        } else {
            LogUtil.i("不存在:" + filePath);
            return false;
        }
    }


//    /**
//     * 安装apk
//     *
//     * @param context
//     * @param downloadApk
//     */
//    public static void installApk(Context context, String downloadApk) {
//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        File file = new File(downloadApk);
//        LogUtil.i("安装路径==" + downloadApk);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            LogUtil.i(getPackageName(context));
////            Uri apkUri = FileProvider.getUriForFile(context, getPackageName(context) + ".fileProvider", file);
//            Uri apkUri = getUriFromFile(context, file);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
//        } else {
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            Uri uri = Uri.fromFile(file);
//            intent.setDataAndType(uri, "application/vnd.android.package-archive");
//        }
//        context.startActivity(intent);
//
//    }


    public static void installApk(Activity context, String path) {
        int REQUEST_CODE_UNKNOWN_APP = 88;
        LogUtil.i("安装路径==" + path);
        File file = new File(path);
        if (file.exists()) {
            Intent installApkIntent = new Intent();
            installApkIntent.setAction(Intent.ACTION_VIEW);
            installApkIntent.addCategory(Intent.CATEGORY_DEFAULT);
            installApkIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //适配8.0需要有权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                boolean hasInstallPermission = context.getPackageManager().canRequestPackageInstalls();
                if (hasInstallPermission) {
                    //安装应用
                    installApkIntent.setDataAndType(FileProvider.getUriForFile(context.getApplicationContext(), context.getPackageName() + ".fileProvider", file), "application/vnd.android.package-archive");
                    installApkIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    if (context.getPackageManager().queryIntentActivities(installApkIntent, 0).size() > 0) {
                        context.startActivity(installApkIntent);
                    }
                } else {
                    //跳转至“安装未知应用”权限界面，引导用户开启权限
                    Uri selfPackageUri = Uri.parse("package:" + context.getPackageName());
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, selfPackageUri);
                    context.startActivityForResult(intent, REQUEST_CODE_UNKNOWN_APP);
                }
            } else {
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                    installApkIntent.setDataAndType(FileProvider.getUriForFile(context.getApplicationContext(), context.getPackageName() + ".fileProvider", file), "application/vnd.android.package-archive");
                    installApkIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } else {
                    installApkIntent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                }
                if (context.getPackageManager().queryIntentActivities(installApkIntent, 0).size() > 0) {
                    context.startActivity(installApkIntent);
                }
            }
        }
    }

    /**
     * file --> uri
     *
     * @param context
     * @param file
     * @return
     */
    public static Uri getUriFromFile(Context context, File file) {
        if (context == null || file == null) {
            throw new NullPointerException();
        }
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            uri = FileProviderUtils.getUriForFile24(context, file);
            uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", file);
        } else {
            uri = FileProviderUtils.getUriForFile(context, file);
        }
        return uri;
    }
}
